package cn.wuqingna.legendgem.loader

import cn.wuqingna.legendgem.conditions.Condition
import cn.wuqingna.legendgem.conditions.ConditionGroup
import cn.wuqingna.legendgem.util.info
import cn.wuqingna.legendgem.util.listFile
import cn.wuqingna.legendgem.util.newfolder
import org.bukkit.configuration.ConfigurationSection
import org.bukkit.configuration.file.YamlConfiguration
import taboolib.common.LifeCycle
import taboolib.common.platform.Awake
import taboolib.platform.BukkitPlugin

object ConditionsLoader {
    private val folder = newfolder(BukkitPlugin.getInstance().dataFolder, "conditions", listOf("conditions.yml"))
    val conditions = mutableMapOf<String, ConditionGroup>()
    @Awake(LifeCycle.ENABLE)
    fun loader(){
        conditions.clear()
        folder.listFile("yml").forEach { file ->
            YamlConfiguration.loadConfiguration(file).apply {
                getKeys(false).forEach {
                    val key = it
                    val config = this.getConfigurationSection(it)
                    conditions[key] = getConditionGroup(config)
                }
            }
            info(" Loader ConditionGroups §c${conditions.size}§f.")
        }
    }

    fun getConditionGroup(section: ConfigurationSection): ConditionGroup{
        val embed = section.getMapList("embed").map{
            Condition(it["if"]?.toString() ?: it["$"]?.toString() ?: "false", it["message"].toString(), it["consume"]?.toString())
        }.toMutableList()
        val takeGem = section.getMapList("take-gem").map{
            Condition(it["if"]?.toString() ?: it["$"]?.toString() ?: "false", it["message"].toString(), it["consume"]?.toString())
        }.toMutableList()

        return ConditionGroup(embed, takeGem)

    }

}